﻿using DataSync.Common;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Boco.CommonLib;
using System.IO;
using DataSync.Entity;

namespace DataSync.Proc
{
    class DataFileClean : TaskBase
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        List<FileCleanConfig> CleanConfig;

        public DataFileClean(TaskConf conf) : base(conf)
        {
        }

        public override void Init()
        {
            CleanConfig = new List<FileCleanConfig>();
            var config = TaskConfig.GetTaskConfig(CurTaskConfig.Id);
            var PathConf = config.Element("DataFilePath").Elements("Path");
            foreach (var item in PathConf)
            {
                CleanConfig.Add(new FileCleanConfig()
                {
                    Path = item.Value,
                    SaveDays = item.GetAttributesAsInt("SaveDays"),
                    SaveHours = item.GetAttributesAsInt("SaveHours"),
                    IncludeChildPath = item.GetAttributesAsBool("IncludeChildPath")
                });

            }
        }

        public override void Run()
        {
            //删除文件
            foreach (var item in CleanConfig)
            {
                DeleteBackFile(item);
            }
        }

        void DeleteBackFile(FileCleanConfig conf)
        {
            DateTime delTime = DateTime.MinValue;
            if (conf.SaveDays > 0)
            {
                delTime = DateTime.Now.AddDays(0 - conf.SaveDays);
            }
            if (conf.SaveHours > 0)
            {
                delTime = DateTime.Now.AddHours(0 - conf.SaveHours);
            }

            List<string> Paths = new List<string>();
            //判断是否有子目录方式
            if (conf.IncludeChildPath)
            {
                //需要检查 该目录下子目录
                Paths.AddRange(Directory.GetDirectories(conf.Path));
            }
            else
            {
                Paths.Add(conf.Path);
            }

            int num = 0;
            foreach (var path in Paths)
            {
                log.InfoFormat("检查{0}目录下{1}前的文件", path, delTime);
                try
                {
                    List<string> fileList = GetFilesList(conf.Path);
                    foreach (string file in fileList)
                    {
                        FileInfo finfo = new FileInfo(file);
                        if (finfo.LastWriteTime < delTime)
                        {
                            File.Delete(file);
                            num++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Warn("删除历史文件出错", ex);
                }
            }

            log.InfoFormat("删除{0}目录下文件完成，本次成功删除{1}个", conf.Path, num);
        }

        /// <summary>
        /// 获取目录下的所有文件名，包含子目录下的文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        List<string> GetFilesList(string path)
        {
            string[] files = Directory.GetFiles(path);
            List<string> fileList = new List<string>(files);

            string[] subPath = Directory.GetDirectories(path);
            foreach (string pp in subPath)
            {
                fileList.AddRange(GetFilesList(pp));
            }

            return fileList;
        }
    }
}
